﻿// MIT License
// 开源地址：https://gitee.com/co1024/AbcMvc
// Copyright (c) 2021-2022 1024
// Abc.Mvc=Furion+EF+SqlSugar+Pear layui admin.

using Furion.DynamicApiController;

namespace Abc.Application;

/// <summary>
/// 数据字典
/// </summary>
[ApiDescriptionSettings("HtAdmin", Name = "DataDictionary")]
[AuthorityController(area: "API", controller: "DataDictionary", controllerDescription: "数据字典", PCode = "API")]
public class DataDictionaryService : IDynamicApiController
{
    private readonly ILogger<DataConfigService> _logger;
    private readonly ISqlSugarClient _db;

    public DataDictionaryService(ILogger<DataConfigService> logger
    , ISqlSugarClient db)
    {
        _logger = logger;
        _db = db;
    }

    /// <summary>
    /// 新增或更新一条
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [MaPermission(name: "新增或更新一条", actions: "InsertOrUpdate")]
    public async Task InsertOrUpdate(DataDictionaryInput input)
    {
        if (input.Id > 0)
        {
            //验证 父级下 唯一 Key是否存在
            var isexit = await _db.Queryable<SysDataConfig>().AnyAsync(o => o.PKey == input.PKey && o.Name == input.Name && o.Id != input.Id);
            if (isexit)
            {
                throw Oops.Bah("名称已存在，请检查后重试！");
            }
            var dbentity = await _db.Queryable<SysDataConfig>().FirstAsync(o => o.Id == input.Id.Value);
            input.Adapt(dbentity);
            await _db.Updateable(dbentity).ExecuteCommandAsync();
        }
        else
        {
            //验证 父级下 唯一 Key是否存在
            var isexit = await _db.Queryable<SysDataConfig>().AnyAsync(o => o.PKey == input.PKey && o.Name == input.Name);
            if (isexit)
            {
                throw Oops.Bah("名称已存在，请检查后重试！");
            }
            var addentity = input.Adapt<SysDataConfig>();

            //var newEntity = await _dataConfigRepository.InsertAsync(addentity);
            var result = await _db.Insertable<SysDataConfig>(addentity).ExecuteCommandAsync();
        }
    }

    /// <summary>
    /// 分页查询
    /// </summary>
    /// <param name="searchQuery"></param>
    /// <returns></returns>
    [MaPermission(name: "分页查询", actions: "GetAllByPage")]
    public async Task<PagedList<DataDictionaryOut>> GetAllByPage(DataDictionaryQuery searchQuery)
    {
        var queryable = _db.Queryable<SysDataConfig>();
        if (!string.IsNullOrWhiteSpace(searchQuery.Pkey))
        {
            queryable = queryable.Where(o => o.PKey == searchQuery.Pkey);
        }

        return await queryable.ToPagedListAsync<SysDataConfig, DataDictionaryOut>(searchQuery.Page, searchQuery.Limit);
    }
}